<script lang="ts" setup>
import { computed, onMounted, ref } from 'vue';

import { preferences, usePreferences } from '@vben/preferences';

import { Button, Checkbox } from 'ant-design-vue';

import { BASE_ICON_URL } from '#/config'; // 引入全局配置

interface RoomList {
  id: number;
  nameZh: string;
}
// 定义 props 来接收父组件传递的数据
const props = defineProps<{
  roomList: RoomList[];
  selectIds: null | number[] | string[] | undefined;
}>();

const emit = defineEmits(['change']);

// 使用 usePreferences 函数获取主题相关信息
const { isDark } = usePreferences();

// 计算当前主题
const currentTheme = computed(() => {
  if (preferences.theme.mode === 'auto') {
    return isDark.value ? 'dark' : 'light';
  }
  return preferences.theme.mode;
});

// 选中的房型id
const selectedRoomId = ref<number[]>([]);

onMounted(() => {
  selectedRoomId.value = props.selectIds?.map(Number) || [];
});
const change = (id: number) => {
  const index = selectedRoomId.value.indexOf(id);
  if (index === -1) {
    selectedRoomId.value.push(id);
  } else {
    selectedRoomId.value.splice(index, 1);
  }
  emit('change', selectedRoomId.value);
};
// 是否展开全部
const isExpandAll = ref(false);
// 全选
const selectAll = () => {
  isExpandAll.value = true;
  selectedRoomId.value = props.roomList?.map((item) => item.id) || [];
  emit('change', selectedRoomId.value);
};
// 清除全部
const clear = () => {
  selectedRoomId.value = [];
  emit('change', selectedRoomId.value);
};
</script>

<template>
  <div class="room">
    <div class="flex items-center">
      <Button class="w-auto pl-0" type="link" @click="selectAll">全选</Button>
      <Button class="w-auto px-1" type="link" @click="clear">清空</Button>
    </div>
    <div v-for="(item, index) in roomList" :key="item.id">
      <div v-if="roomList.length < 4 || index < 4 || isExpandAll" class="py-2">
        <Checkbox
          :checked="selectedRoomId?.includes(item.id)"
          @change="change(item.id)"
        >
          <div :class="currentTheme">{{ item.nameZh }}</div>
        </Checkbox>
      </div>
    </div>
    <button
      v-if="roomList.length > 4"
      :class="currentTheme"
      class="more my-0 flex items-center px-0 py-1"
      @click="isExpandAll = !isExpandAll"
    >
      {{ isExpandAll ? '收起' : '更多' }}
      <img
        :src="`${BASE_ICON_URL}${isExpandAll ? 'icons-20.png' : 'icons-19.png'}`"
        class="ml-1 h-4 w-4"
      />
    </button>
  </div>
</template>

<style lang="scss" scoped>
.more {
  cursor: pointer;
}

.light {
  color: hsl(var(--card-foreground));
}

.more:hover {
  color: hsl(var(--primary));
}

.dark img {
  filter: invert(1);
}
</style>
